package com.example.studentknowledge.controller;

import com.example.studentknowledge.entity.Article;
import com.example.studentknowledge.entity.User;
import com.example.studentknowledge.service.ArticleService;
import com.example.studentknowledge.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 文章控制器
 */
@RestController
@RequestMapping("/api/articles")
@CrossOrigin(origins = "*")
public class ArticleController {
    
    @Autowired
    private ArticleService articleService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 创建文章
     */
    @PostMapping
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> createArticle(@Valid @RequestBody Article article, Authentication authentication) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                article.setAuthor(user.get());
                Article savedArticle = articleService.createArticle(article);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "文章创建成功");
                response.put("article", savedArticle);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新文章
     */
    @PutMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> updateArticle(@PathVariable Long id, @Valid @RequestBody Article article, Authentication authentication) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                article.setId(id);
                Article updatedArticle = articleService.updateArticle(article, user.get());
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "文章更新成功");
                response.put("article", updatedArticle);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据ID获取文章
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getArticleById(@PathVariable Long id) {
        try {
            Article article = articleService.viewArticle(id);
            return ResponseEntity.ok(article);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取已发布的文章列表
     */
    @GetMapping
    public ResponseEntity<?> getPublishedArticles(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Article> articles = articleService.getPublishedArticles(pageable);
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据作者获取文章
     */
    @GetMapping("/author/{authorId}")
    public ResponseEntity<?> getArticlesByAuthor(
            @PathVariable Long authorId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Optional<User> author = userService.findById(authorId);
            if (author.isPresent()) {
                Pageable pageable = PageRequest.of(page, size);
                Page<Article> articles = articleService.getArticlesByAuthor(author.get(), pageable);
                return ResponseEntity.ok(articles);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据分类获取文章
     */
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<?> getArticlesByCategory(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Article> articles = articleService.getArticlesByCategory(categoryId, pageable);
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 搜索文章
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchArticles(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Article> articles = articleService.searchArticles(keyword, pageable);
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取热门文章
     */
    @GetMapping("/popular")
    public ResponseEntity<?> getPopularArticles(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Article> articles = articleService.getPopularArticles(limit);
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取最新文章
     */
    @GetMapping("/latest")
    public ResponseEntity<?> getLatestArticles(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Article> articles = articleService.getLatestArticles(limit);
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取推荐文章
     */
    @GetMapping("/recommended")
    public ResponseEntity<?> getRecommendedArticles(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Article> articles = articleService.getRecommendedArticles(limit);
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据日期范围获取文章
     */
    @GetMapping("/date-range")
    public ResponseEntity<?> getArticlesByDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Article> articles = articleService.getArticlesByDateRange(startDate, endDate, pageable);
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 点赞文章
     */
    @PostMapping("/{id}/like")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> likeArticle(@PathVariable Long id, Authentication authentication) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                boolean liked = articleService.toggleLike(id, user.get());
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", liked ? "点赞成功" : "取消点赞成功");
                response.put("liked", liked);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除文章
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> deleteArticle(@PathVariable Long id, Authentication authentication) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                articleService.deleteArticle(id, user.get());
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "文章删除成功");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取我的文章
     */
    @GetMapping("/my")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> getMyArticles(
            Authentication authentication,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                Pageable pageable = PageRequest.of(page, size);
                Page<Article> articles = articleService.getArticlesByAuthor(user.get(), pageable);
                return ResponseEntity.ok(articles);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}